package com.springcloud.store.feign;

import com.springcloud.commom.api.R;
import com.springcloud.commom.exception.ServiceException;
import com.springcloud.stock.entity.Product;
import com.springcloud.stock.feign.IStoreClient;
import com.springcloud.store.modular.product.service.ProductService;
import io.seata.core.context.RootContext;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

@RestController
@AllArgsConstructor
@Slf4j
public class StoreClient implements IStoreClient {

    ProductService productService;

    @Override
    public R<String> decreaseStore(String id, Integer num) {
        log.info("store-service begin,XID：{}", RootContext.getXID());
        Product product = productService.getById(id);

        if(product == null){
            throw new ServiceException("商品不存在!");
        }

        Integer total = product.getProductCount();
        Integer count = total - num;

        if(count < 0){
            throw new ServiceException("商品库存不足!");
        }

        product.setProductCount(count);

        productService.updateById(product);

        return R.success();
    }
}
